import React, { Component } from 'react'
import { Card, Button, Table, Tooltip, Image, Tag, Modal, message } from 'antd'
import dayjs from 'dayjs'
import XLSX from 'xlsx'
import { fetchItems, delItem } from '@api'
export default class ItemList extends Component {
  constructor() {
    super();
    this.state = {
      page: 1,
      pageSize: 10,
      total: 0, // 总条数
      items: [],
      loading: false,
      columns: [
        //  表格的每一列
        {
          title: '名称',
          dataIndex: 'name',
          key: 'name'
        },
        {
          title: '描述',
          dataIndex: 'desc',
          render: (value, row, index) => {
            return (
              <Tooltip title={value}>
                <span>
                  {value.substr(0, 10) + '...'}
                </span>
              </Tooltip>
            )
          },
          key: 'desc'
        },
        {
          title: '价格',
          dataIndex: 'price',
          render: (value) => {
            return (
              <span>￥{value}</span>
            )
          },
          key: 'price'
        },
        {
          title: '库存',
          dataIndex: 'store',
          key: 'store'
        },
        {
          title: '销量',
          dataIndex: 'sale',
          render: (value) => {
            return (
              <Tag color={value > 500 ? 'red' : 'green'}>
                {value}
              </Tag>
            )
          },
          key: 'sale'
        },
        {
          title: '封面',
          dataIndex: 'thumb',
          render: (value) => {
            return (
              <Image width={50} src={value} />
            )
          },
          key: 'thumb'
        },
        {
          title: '上架时间',
          dataIndex: 'createAt',
          render: (value) => {
            return (
              <span>
                {dayjs(value).format('YYYY-MM-DD')}
              </span>
            )
          },
          key: 'createAt'
        },
        {
          title: '操作',
          // 自定义渲染 表单单元格
          render: (id) => {
            return (
              <div>
                <Button 
                  type="primary" 
                  onClick = {
                    () => {
                      this.props.history.push(`/admin/itemUpdate/${id}`)
                    }
                  }
                  size="small">编辑</Button>
                <Button 
                  danger 
                  size="small"
                  onClick = {
                    ()=>{
                      this.delItem(id)
                    }
                  }
                  >删除</Button>
              </div>
            )
          },
          dataIndex: 'id',
          key: 'action'
        }
      ],
      // 导出为excel的数据
      data: [
        
      ]
    }
  };
  render() {

    return (
      <Card title="商品管理" 
        extra={<Button onClick = {
          this.exportFile
        }>导入为excel</Button>}>
        <Button 
          type="primary" 
          onClick = {
            () => {
              this.props.history.push('/admin/itemAdd')
            }
          }
          style={{ marginBottom: 20 }}>增加商品</Button>
        <Table
          loading={this.state.loading}
          pagination={
            {
              defaultCurrent: this.state.page,
              pageSize: this.state.pageSize,
              total: this.state.total,
              onChange: this.switchPage
            }
          }
          rowKey="id"
          dataSource={this.state.items} columns={this.state.columns} />
      </Card>
    )
  };
  delItem = (id) => {
    // 删除商品
    Modal.confirm({
      title: '删除商品',
      content:'您确认删除嘛?',
      onOk: () => {
        delItem(id).then(res=> {
          if(res.data.code === 200) {
            message.success(res.data.msg, 2, () => {
              this.props.history.go(0)
            })
          }
        })
      }
    })
  };
  initExcelData = () => {
    // 处理导出excel数据
    let data = [
      ['id','商品名称','商品价格','商品库存','商品描述','商品封面','销量','上架时间','详情']
    ];
    this.state.items.forEach(item => {
      /* console.log(item); */
      data.push(Object.values(item))
    })
    console.log(data);
    this.setState({
      data: data
    })
  };
  // 导出为excel
  exportFile = () => {
    /* convert state to workbook */
    const ws = XLSX.utils.aoa_to_sheet(this.state.data);
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, "SheetJS");
    /* generate XLSX file and send to client */
    XLSX.writeFile(wb, "商品数据.xlsx")
  };
  componentDidMount() {
    this.fetchItems();
  };
  switchPage = (page, pageSize) => {
    // 分页效果
    console.log(page);
    console.log(pageSize);
    this.setState({
      page,
      pageSize
    }, () => {
      // 重新请求下一页数据
      this.fetchItems()
    })
  };
  fetchItems = () => {
    // loading为true
    this.setState({
      loading: true
    })
    fetchItems({
      page: this.state.page,
      pageSize: this.state.pageSize
    }).then(res => {
      this.setState({
        loading: false
      })
      if (res.data.code === 200) {
        this.setState({
          items: res.data.data.list,
          total: res.data.data.total
        }, () => {
          this.initExcelData()
        })
      }
    })
    
  }
}
